package com.yss.controller;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Configuration
public class TestController {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @GetMapping("/route")
    public String route(){
        RestTemplate restTemplate = getRestTemplate();
        String json=restTemplate.getForObject("http://spring-provide-server/call/1",String.class);
        return json;
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping(value = "/lb")
    public ServiceInstance lb() {
        return loadBalancerClient.choose("spring-provide-server");
    }

    @Autowired
    private SpringClientFactory factory;

    @GetMapping(value = "/factory")
    public String getRuleName(){
        ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer)factory.getLoadBalancer("default");
        System.out.println(lb.getRule().getClass().getName());//ZoneAvoidanceRule

        ZoneAwareLoadBalancer lb2 = (ZoneAwareLoadBalancer)factory.getLoadBalancer("spring-provide-server");
        System.out.println(lb2.getRule().getClass().getName());
        return "";
    }
}
